import java.io.*;

public class DirectoryCopy {
    public static void main(String[] args) {
        String sourceDir = "D://";
        String targetDir = "D://";
        String dirName = new File(sourceDir).getName();  // 获取源目录名
        String targetPath = targetDir + File.separator + dirName;  // 完整目标路径
        try {
            copyDirectory(new File(sourceDir), new File(targetDir));
            System.out.println("目录复制完成！");
        }catch (Exception e) {
            System.err.println("目录复制失败！");
        }
    }

    public static void copyDirectory(File sourceDir, File targetDir) throws Exception{
        if (!sourceDir.exists()) {
            System.out.println("源目录不存在:" + sourceDir.getAbsolutePath());
        }
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        File[] files = sourceDir.listFiles();
        if (files != null) {
            for (File file : files) {
                File targetFile = new File(targetDir, file.getName());
                if (file.isDirectory()) {
                    copyDirectory(file,targetFile);
                }else {
                    copyFile(file,targetFile);
                }
            }
        }
    }
    public static void copyFile(File sourceFile, File targetFile) throws Exception {
       try (InputStream in = new FileInputStream(sourceFile); OutputStream out = new FileOutputStream(targetFile)) {
           byte[] buf = new byte[1024];
           int len;
           while ((len = in.read(buf)) > 0) {
               out.write(buf, 0, len);
           }
       }
    }
}
